<template>
  <div class="box">
    <div class="loginBox">
      <!-- 头像框 -->
      <div class="avatar">
        <!-- <img src="../assets/images/avatar.jpg" alt /> -->
        <img :src="'http://127.0.0.1:666/'+avatar" alt />
      </div>
      <!-- 广告 -->
      <div class="banner">
        <img src="../assets/images/study.png" alt />
      </div>
      <!-- 梯子 -->
      <div class="ladder"></div>
      <!-- 表单区域 -->
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" status-icon>
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            prefix-icon="el-icon-user"
            placeholder="学号 / 邮箱"
            clearable
            @blur="getAvatar"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password" ref="password">
          <el-input
            v-model="loginForm.password"
            prefix-icon="el-icon-lock"
            placeholder="密码"
            type="password"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="submitLoginForm('0')">学生登录</el-button>
          <el-button type="primary" @click="submitLoginForm('1')">教师登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义校验规则
    let checkUserName = (rule, value, cbfn) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      // 验证学号的正则表达式
      const regStuNum = /^[0-9]{11}$/

      if (value.includes('@') && !regEmail.test(value)) {
        cbfn(new Error('请输入正确的邮箱格式'))
      } else if (!value.includes('@') && !regStuNum.test(value)) {
        return cbfn(new Error('请输入正确的学号'))
      } else {
        cbfn()
      }
    }
    return {
      // 登录表单
      loginForm: {
        // 登录名称
        username: '',
        // 登录密码
        password: '',
        // 用户角色
        role: ''
      },
      // 保存用户头像信息
      avatar: 'uploads/logo.jpg',
      // 登录表单的校验规则
      loginFormRules: {
        username: [
          { required: true, message: '请输入学号或邮箱', trigger: 'blur' },
          { validator: checkUserName, trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 获得头像信息
    getAvatar() {
      this.$refs.loginFormRef.validateField('username', async valid => {
        // 如果输入的帐号为空或者格式不正确，直接返回
        if (valid !== '') return
        // 发送请求
        let res = await this.$http.get('users/avatar', {
          params: { username: this.loginForm.username }
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取头像信息失败')
        }
        // 获取头像成功
        // this.$message.success('获取头像成功')
        this.avatar = res.data.avatar
        // 保存用户名和头像信息
        localStorage.setItem('userInfo', JSON.stringify(res.data))
      })
    },
    // 提交表单信息
    submitLoginForm(role) {
      this.$refs.loginFormRef.validate(async valid => {
        // 如果验证失败，直接返回
        if (!valid) return
        // 将用户角色保存
        this.loginForm.role = role
        // 验证成功，发起请求
        let res = await this.$http.post('users/login', this.loginForm)
        // 请求失败
        if (res.meta.status !== 200) {
          this.$message({
            message: '帐号或密码错误',
            type: 'error',
            showClose: true
          })
          // 重置密码框
          return this.$refs.password.resetField()
        }
        // 请求成功
        this.$message({
          message: '登录成功',
          type: 'success',
          showClose: true
        })
        // 保存令牌信息到sessionStorage
        localStorage.setItem('token', res.data.token)
        // 使用编程式导航跳转到首页
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.box {
  // background-color: #41b879;
  background-color: #51b066;
  height: 100%;
}
.loginBox {
  width: 450px;
  height: 300px;
  background-color: #fff;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 10px;
  box-shadow: 0 0 5px #fff;
  box-sizing: border-box;
  padding: 70px;
}
.avatar {
  width: 100px;
  height: 100px;
  border: 1px solid #fff;
  position: absolute;
  top: 0;
  left: 0;
  transform: translate(-50%, -50%);
  border-radius: 10px;
  overflow: hidden;
  padding: 5px;
  // background-color: black;
  img {
    width: 100%;
    height: 100%;
    border-radius: 10px;
  }
}
.banner {
  width: 400px;
  height: 200px;
  // border: 1px dashed red;
  position: absolute;
  bottom: 0;
  right: 0;
  transform: translate(50%, 50%);
  border-radius: 10px;
  img {
    width: 100%;
    height: 100%;
  }
}
.ladder {
  width: 200px;
  height: 200px;
  position: absolute;
  bottom: 0;
  left: 0;
  transform: translate(-10%, 10%);
  border-left: 10px solid #fff;
  border-bottom: 10px solid #fff;
  border-radius: 10px;
}
.el-form-item {
  text-align: center;
}
</style>